package com.mytrip.aop;

import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.context.MessageSource;
import org.springframework.context.MessageSourceAware;

import com.mytrip.base.aop.BaseAspect;
import com.mytrip.base.exception.BaseException;
import com.mytrip.webapp.filter.CtxSessionBag;

@Aspect
public class ExceptionHandlerAspect extends BaseAspect implements MessageSourceAware {

	private List<String> actionAccessExcludeList = new ArrayList<String>(0);
	
	private MessageSource messageSource;
		
	public void setActionAccessExcludeList(List<String> actionAccessExcludeList) {
		this.actionAccessExcludeList = actionAccessExcludeList;
	}

	public void setMessageSource(MessageSource messageSource) {
		this.messageSource = messageSource;
	}
	
	// ~ method ==================================================================
	
	@Pointcut("execution(* com.mytrip.dao..*Dao.*(..)) " +
				"|| execution(* com.mytrip.service..*Manager.*(..)) " +
				"|| ((execution(* com.mytrip.webapp.action..*Action.*(..)) || execution(* com.mytrip.webapp..*Action.*(..))) " +
				"    && !execution(* com.mytrip.webapp.action..*Action.get*(..))" +
				"    && !execution(* com.mytrip.webapp.action..*Action.set*(..)))")

	public void exceptionHandlerPt() {
	}

	@Around("exceptionHandlerPt()")
	public Object exceptionHandler(ProceedingJoinPoint pjp)
			throws Throwable {
//		Method method = ((MethodSignature) pjp.getSignature()).getMethod();	
//		System.out.println(method.getName());
//		Locale locale = CtxSessionBag.getSessionBag().getLocale();
//		System.out.println(messageSource.getMessage("W0000004", new String[]{"zhang", "ping"}, locale));

		try {
			return pjp.proceed();
		} catch (BaseException e) {
			Locale locale = CtxSessionBag.getSessionBag()==null?Locale.CHINESE:CtxSessionBag.getSessionBag().getLocale();
			String msg = messageSource.getMessage(e.getErrCode(), e.getParams().toArray(), locale);
			e.setMessage(msg);
			
			throw e;
		}
	}

}
